"""
用户认证视图模块 - 使用 JWT 认证
"""
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate, get_user_model
from .serializers import UserSerializer, UserRegisterSerializer, ChangePasswordSerializer

User = get_user_model()


@api_view(['POST'])
@permission_classes([AllowAny])
def register(request):
    """
    用户注册接口
    POST /creation/auth/register
    """
    serializer = UserRegisterSerializer(data=request.data)
    
    if serializer.is_valid():
        # 检查用户名是否已存在
        if User.objects.filter(username=serializer.validated_data['username']).exists():
            return Response({
                'code': 400,
                'message': '用户名已存在',
                'data': None
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 创建用户
        user = serializer.save()
        
        # 生成 JWT Token
        refresh = RefreshToken.for_user(user)
        
        return Response({
            'code': 200,
            'message': '注册成功',
            'data': {
                'user_id': user.id,
                'username': user.username,
                'email': user.email,
                'token': str(refresh.access_token),
                'refresh': str(refresh)
            }
        }, status=status.HTTP_201_CREATED)
    
    return Response({
        'code': 400,
        'message': '参数错误',
        'data': serializer.errors
    }, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([AllowAny])
def login(request):
    """
    用户登录接口
    POST /creation/auth/login
    """
    username = request.data.get('username')
    password = request.data.get('password')
    
    if not username or not password:
        return Response({
            'code': 400,
            'message': '用户名和密码不能为空',
            'data': None
        }, status=status.HTTP_400_BAD_REQUEST)
    
    # 验证用户
    user = authenticate(username=username, password=password)
    
    if user:
        # 生成 JWT Token
        refresh = RefreshToken.for_user(user)
        
        return Response({
            'code': 200,
            'message': '登录成功',
            'data': {
                'user_id': user.id,
                'username': user.username,
                'email': user.email,
                'avatar': user.avatar.url if user.avatar else None,
                'is_staff': user.is_staff,
                'token': str(refresh.access_token),
                'refresh': str(refresh)
            }
        })
    
    return Response({
        'code': 401,
        'message': '用户名或密码错误',
        'data': None
    }, status=status.HTTP_401_UNAUTHORIZED)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def user_info(request):
    """
    获取当前登录用户信息
    GET /creation/auth/info
    """
    serializer = UserSerializer(request.user)
    return Response({
        'code': 200,
        'message': '成功',
        'data': serializer.data
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def update_profile(request):
    """
    更新用户信息
    POST /creation/auth/update
    """
    serializer = UserSerializer(request.user, data=request.data, partial=True)
    
    if serializer.is_valid():
        serializer.save()
        return Response({
            'code': 200,
            'message': '更新成功',
            'data': serializer.data
        })
    
    return Response({
        'code': 400,
        'message': '参数错误',
        'data': serializer.errors
    }, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def change_password(request):
    """
    修改密码
    POST /creation/auth/change-password
    """
    serializer = ChangePasswordSerializer(data=request.data)
    
    if serializer.is_valid():
        user = request.user
        
        # 验证旧密码
        if not user.check_password(serializer.validated_data['old_password']):
            return Response({
                'code': 400,
                'message': '旧密码错误',
                'data': None
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 设置新密码
        user.set_password(serializer.validated_data['new_password'])
        user.save()
        
        return Response({
            'code': 200,
            'message': '密码修改成功',
            'data': None
        })
    
    return Response({
        'code': 400,
        'message': '参数错误',
        'data': serializer.errors
    }, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def logout(request):
    """
    用户登出接口
    POST /creation/auth/logout
    注：JWT 是无状态的，登出只需客户端删除 token 即可
    """
    return Response({
        'code': 200,
        'message': '登出成功',
        'data': None
    })
